<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>远程唤醒</title>
		<meta name="author" content="HaiLaz">
		<!-- App Favicon -->
		<link rel="shortcut icon" href="/static/favicon.ico">

		<!-- Bootstrap CSS -->
		<link href="/static/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

		<!-- App CSS -->
		<link href="/static/css/style.css" rel="stylesheet" type="text/css" />
		<!-- jQuery  -->
		<script src="/static/js/jquery.min.js"></script>
		<script src="/static/js/bootstrap.min.js"></script>
		<script src="/static/js/jquery.qrcode.js"></script>
	</head>
	<body>
		<div class="wrapper" style="margin-top: 15px;">
			<div class="container-fluid">
				<div class="row">
					<div class="col-12" style="margin: 0 auto;max-width: 700px;">
						<div class="card-box">
							<div class="form-group">
								<label for="userName">用户名<span class="text-danger">*</span></label>
								<input type="text" name="nick" parsley-trigger="change" required="" placeholder="待输入" class="form-control" id="userName"
								 data-parsley-id="4" value="">
							</div>
							<div class="text-right">
								<button id="loginbtn" class="btn btn-primary waves-effect waves-light">
									登陆
								</button>
								<button id="logoutbtn" class="btn btn-danger waves-effect waves-light" style="display: none;">
									退出
								</button>
							</div>
						</div>
						<div id="cView" class="" style="display: none;">
							<div class="card-box">
								<h4 class="header-title m-t-0 m-b-10">电脑列表<span id="clientstatus">（APP离线）</span></h4>
								<div class="table-responsive">
									<table class="table table-bordered mb-0">
										<thead>
											<tr>
												<th>别名</th>
												<th>mac地址</th>
												<th>ip</th>
												<th>状态</th>
												<th>操作</th>
											</tr>
										</thead>
										<tbody id="pclist">
										</tbody>
									</table>
								</div>
							</div>
						</div>
						<div class="card-box">
							<center>
								<div id="qrcode" style="display: none;">
									<span>远端APP下载</span>
									<br>
									<div class="sidebar_qrcode_img"></div>
								</div>
								<div id="downloadlink" style="display: none;">
									<a id="appLink" href="">远端APP下载</a>
								</div>
								<a href="#readme">使用说明</a>
							</center>
						</div>
						<div class="card-box">
							<h4 class="header-title m-t-0 m-b-10" id="readme">使用说明</h4>
							<center>
								<span>特别提醒：网卡设置允许魔包唤醒，win10需要关闭快速启动，BIOS设在允许wol唤醒（某些电脑需要网卡第一启动项）。</span>
								<br>
								<img src="/static/app/wakeonlan.png" style="width: 100%;">
							</center>
						</div>
						<div class="card-box">
							<h4 class="header-title m-t-0 m-b-10">日志</h4>
							<textarea id="logs" class="form-control" rows="15" placeholder="日志" readonly="ture"></textarea>
						</div>
					</div>
					<!-- end col-12 -->
				</div> <!-- end row -->
			</div> <!-- container -->

		</div> <!-- End wrapper -->
		<!-- Begin page -->

		<script type="text/javascript">
			//全局变量
			var codeSave = 200
			var codeLogout = 100 //退出
			var codeLogin = 101 //登陆
			var codeSetPC = 102 //设置电脑
			var codeWol = 666 //唤醒
			var codeExist = 998 //不可重复登录
			var codeError = 999 //错误
			var codeHeartbeat = 1000 //心跳
			var typeClient = 1 //客户端
			var typeControl = 2 //控制端

			var isConnect = false;
			var isLogIN = false;
			var Cname = "";
			var Ctype = typeControl;
			var PcList = new Array();
			var KeepAliveInterval = 0;
			var reflashInterval = 0;
			var baseServer = window.location.host;
			console.log(baseServer);
			//var baseServer = "localhost:8066";
			var WebSocketURL = "ws://" + baseServer + "/ws";
			var WOLPort = 9;
			var MyWebSocket;
			//页面初始化
			$(function() {
				$("#loginbtn").attr("disabled", true);
				$("#addpc").attr("disabled", true);
				WsConnect();
				ListenBtnOn();
				$("#userName").focus();
			})
			$(document).keyup(function(event) {
				if (event.keyCode == 13) {
					$("#loginbtn").trigger("click");
				}
			});
		</script>
		<script type="text/javascript">
			//定时器模块

			//保持ws连接
			function StartKeepAlive(sec) {
				StopKeepAlive();
				KeepAliveInterval = setInterval(function() {
					SendHeartbeat();
				}, sec * 1000);
			}

			function StopKeepAlive() {
				if (KeepAliveInterval != 0) {
					clearInterval(KeepAliveInterval);
				}
			}
			//定时刷新设备列表
			function StartReflash(sec) {
				StopReflash();
				SendGetPCList();
				reflashInterval = setInterval(function() {
					SendGetPCList();
				}, sec * 1000);
			}

			function StopReflash() {
				if (reflashInterval != 0) {
					clearInterval(reflashInterval);
				}
			}
		</script>
		<script>
			var appDownloadLink = "http://" + baseServer + "/static/app/wakeonlan.apk";
			var browser = {
				versions: function() {
					var u = navigator.userAgent,
						app = navigator.appVersion;
					return {
						trident: u.indexOf('Trident') > -1, //IE内核
						presto: u.indexOf('Presto') > -1, //opera内核
						webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
						gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
						mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
						ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
						android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
						iPhone: u.indexOf('iPhone') > -1, //是否为iPhone
						iPad: u.indexOf('iPad') > -1, //是否iPad
					};
				}(),
				language: (navigator.browserLanguage || navigator.language).toLowerCase()
			};
			$(function() {
				if (browser.versions.mobile) {
					$("#appLink").attr("href", appDownloadLink);
					$("#qrcode").hide();
					$("#downloadlink").show();
				} else {
					$('.sidebar_qrcode_img').qrcode({
						text: appDownloadLink,
						height: 150,
						width: 150,
						//src: 'img/Love100x100.jpg',
						percen: 0.3,
						background: "white",
						foreground: "black"
					})
					$("#qrcode").show();
					$("#downloadlink").hide();
				}
			})
		</script>
		<script type="text/javascript">
			//页面交互

			function ListenBtnOn() {
				$("#loginbtn").on('click', function() {
					LogIn();
				});
				$("#logoutbtn").on('click', function() {
					LogOut();
					isLogIN = false;
				});
				$("#addpc").on('click', function() {
					var pcname = $("#pcname").val();
					var pcmac = $("#pcmac").val();
					pcmac = pcmac.toUpperCase();
					var pcip = $("#pcip").val();
					//mac地址正则表达式 
					var reg_name = /[A-F\d]{2}-[A-F\d]{2}-[A-F\d]{2}-[A-F\d]{2}-[A-F\d]{2}-[A-F\d]{2}/;
					if (!reg_name.test(pcmac)) {
						mui.alert("mac地址格式不正确！mac地址格式为FF-FF-FF-FF-FF-FF", '提示', function() {});
						return;
					}
					if (SendAddPC(pcname, pcmac, pcip)) {
						$("#addPCLi").removeClass("mui-active");
					} else {
						mui.alert("mac重复", '提示', function() {});
					}

				});
			}

			function SetIsLogin(is) {
				if (is) {
					$("#userName").attr("disabled", true);
					$("#loginbtn").hide();
					$("#logoutbtn").show();
					$("#cView").show();
					if (!isLogIN) {
						ShowLog("已登录");
						isLogIN = is;
					}
				} else {
					$("#userName").attr("disabled", false);
					$("#loginbtn").show();
					$("#logoutbtn").hide();
					$("#cView").hide();
					ShowLog("已退出");
				}
			}

			function LogIn() {
				if ($("#userName").val().length == 0) {
					alert('请输入用户名');
					return;
				}
				Cname = $("#userName").val();
				StartReflash(5);
			}


			function LogOut() {
				Cname = "";
				PcList = new Array();
				StopReflash();
				ClearPCList();
				SetIsLogin(false);
			}


			function SetConnectStatus(is) {
				if (is) {
					ShowLog("服务器已连接");
					isConnect = true;
					$("#loginbtn").attr("disabled", false);
					$("#addpc").attr("disabled", false);
					StopKeepAlive();
					if (isLogIN) {
						LogIn();
					}
				} else {
					ShowLog("服务器已断开");
					if (isLogIN) {
						LogOut();
					}
					isConnect = false;
					$("#loginbtn").attr("disabled", true);
					$("#addpc").attr("disabled", true);
					StartKeepAlive(1); //断开后自动重连
				}
			}


			function ShowLog(t) {
				console.log(t);
				var myDate = new Date()
				$("#logs").text(myDate.Format("MM月dd日hh:mm:ss：\n") + t + "\n" + $("#logs").text());
			}

			function ClearPCList() {
				var ul = $("#pclist").html("");
				if (PcList.length == 0) {
					ul.html('<tr><th class="text-muted">列表为空</th><td><td><td><td></tr>');
				}
			}
			//
			function ShowPCList() {
				ClearPCList();
				var ul = $("#pclist");
				for (var i = 0; i < PcList.length; i++) {
					var name = PcList[i].name;
					var mac = PcList[i].mac;
					var ip = PcList[i].ip;
					var status = PcList[i].status;

					var tr = $("<tr>");
					var th = $("<th>").addClass("text-muted").text(name);
					var tdmac = $("<td>").text(mac);
					var tdip = $("<td>").text(ip);
					var tdstatus = $("<td>").text(status == 1 ? '在线' : '离线');
					var tdbtn = $("<td>").attr("id", 'p-' + i);
					var wakeBtn = $("<button>").addClass("btn btn-primary waves-effect waves-light").text("唤醒");
					wakeBtn.on('click', function() {
						PCListBtnOn($(this), 1);
					});
					tr.append(th, tdmac, tdip, tdstatus, tdbtn.append(wakeBtn));
					ul.append(tr);
				}
			}

			//设备列表按钮
			function PCListBtnOn(btn, type) {
				var parent = btn.parent();
				var pId = parent.attr("id").split("-")[1];
				switch (type) {
					case 1:
						var pc = new Array();
						pc.push(PcList[pId]);
						SendWol(pc);
						break;
					case 2:
						var btnArray = ['否', '是'];
						mui.confirm('确认？', '删除设备', btnArray, function(e) {
							if (e.index == 1) {
								SendDelPC(pId);
							} else {}
						})
						break;
				}
			}
		</script>

		<script type="text/javascript">
			//websocket模块
			function WsConnect() {
				ShowLog("正在连接服务器...");
				MyWebSocket = new WebSocket(WebSocketURL);

				MyWebSocket.onopen = function(evt) {
					//StartKeepAlive(5); //保持心跳
					SetConnectStatus(true)
					//MyWebSocket.send('{"code":101,"name":"hello","type":1,"pc":[{"mac":"ff-ff-ff-ff-ff-ff","name":""}],"data":""}');
				};

				MyWebSocket.onclose = function() {
					//StopKeepAlive();
					SetConnectStatus(false)
					if (MyWebSocket.readyState == 3) {
						ShowLog("等待重连服务器...");
						setTimeout("WsConnect()", 3000); //断开后自动重连
					}
				};

				MyWebSocket.onerror = function(evt) {

				};

				MyWebSocket.onmessage = function(evt) {
					console.log("Received Message: " + evt.data);
					var command = JSON.parse(evt.data);
					switch (command.code) {
						case codeWol:
							WolPC(command.pc)
							break;
						case codeSetPC:
							if (command.clientstatus == 1) {
								$("#clientstatus").text("（APP在线）");
							} else {
								$("#clientstatus").text("（APP离线）");
							}
							PcList = command.pc;
							ShowPCList();
							SetIsLogin(true);
							break;
						case codeExist:
							console.log(command.data)
							isLogIN = false;
							LogOut();
							alert(command.data);
							break;
						case codeError:
							alert(command.data);
							break;
						default:
							break;
					}
				};
			}

			function WebSocketColse() {
				if (isConnect) {
					MyWebSocket.close();
				}
			}

			function WebSocketSend(obj) {
				if (isConnect) {
					MyWebSocket.send(JSON.stringify(obj));
				}
			}


			function WolPC(pcList) {
				for (var i = 0; i < pcList.length; i++) {
					var mac = pcList[i].mac;
					var name = pcList[i].name;
					//UDPWOL("255.255.255.255", 6666, '00-15-5D-00-70-34');
					UDPWOL("255.255.255.255", WOLPort, mac);
				}
			}

			function SendHeartbeat() {
				WebSocketSend(GetWsMsgObj(codeHeartbeat, [], ""));
			}

			function SendWol(pc) {
				WebSocketSend(GetWsMsgObj(codeWol, pc, ""));
			}

			function SendGetPCList() {
				WebSocketSend(GetWsMsgObj(codeLogin, [], ""));
			}

			function SendLogout() {
				WebSocketSend(GetWsMsgObj(codeLogout, [], ""));
			}


			function SendSave() {
				WebSocketSend(GetWsMsgObj(codeSave, PcList, ""));
				SendGetPCList();
			}

			function SendDelPC(pid) {
				PcList.splice(pid, 1);
				SendSave();
			}

			function SendAddPC(name, mac, ip) {
				var has = false;
				for (var i = 0; i < PcList.length; i++) {
					if (PcList[i].mac == mac) {
						has = true;
						break;
					}
				}
				if (!has) {
					PcList.push({
						mac: mac,
						name: name,
						ip: ip
					});
					SendSave();
				}
				return !has;
			}

			function GetWsMsgObj(code, pc, data) {
				var obj = {
					code: code,
					name: Cname,
					type: Ctype,
					pc: pc,
					data: data
				}
				return obj;
			}
		</script>
		<script type="text/javascript">
			// 对Date的扩展，将 Date 转化为指定格式的String   
			// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
			// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
			// 例子：   
			// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
			// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
			Date.prototype.Format = function(fmt) { //author: meizz   
				var o = {
					"M+": this.getMonth() + 1, //月份   
					"d+": this.getDate(), //日   
					"h+": this.getHours(), //小时   
					"m+": this.getMinutes(), //分   
					"s+": this.getSeconds(), //秒   
					"q+": Math.floor((this.getMonth() + 3) / 3), //季度   
					"S": this.getMilliseconds() //毫秒   
				};
				if (/(y+)/.test(fmt))
					fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
				for (var k in o)
					if (new RegExp("(" + k + ")").test(fmt))
						fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				return fmt;
			}
		</script>
	</body>
</html>
